[大谦Excel,dqexcel点com]
数据查询
【问题描述】
查询指定时间点或时间段的数据。
【示例7-3】
本例使用示例7-2的数据,请查询每天中午12点时的测量值。
- 编写下面的代码:
code.python
import pandas as pd
# 通过pandas读取Excel文件
df = pd.read_excel('D:/Samples/ch07/01 时间序列数据/时间序列.xlsx', engine='openpyxl', sheet_name=0, index_col=0)
# 查询每天中午12点时的测量值
measurement = df.at_time('12:00')
# 打印查询结果
print(measurement)
打开Python IDLE,新建一个脚本文件,将上面生成的代码复制进去,保存。运行脚本,在IDLE Shell窗口输出每天12点的测量值。
code.python
>>> == RESTART: D:/Samples/1.py =
测量值
时间
2022-03-18 12:00:00 7
2022-03-19 12:00:00 8
2022-03-20 12:00:00 2
2022-03-21 12:00:00 9
数据筛选
【问题描述】
根据指定条件筛选出一部分数据。
【示例7-4】
本例使用示例7-2的数据,请查询每天中午12点时的测量值。
- 编写下面的代码:
code.python
import pandas as pd
# 通过pandas读取Excel文件中的第一个工作表,指定第一列作为索引列,引擎为"openpyxl"
df = pd.read_excel('D:/Samples/ch07/01 时间序列数据/时间序列.xlsx', sheet_name=0, index_col=0, engine="openpyxl")
# 筛选出测量值大于等于9的数据
result = df[df['测量值'] >= 9]
print(result)
打开Python IDLE,新建一个脚本文件,将上面生成的代码复制进去,保存。运行脚本,在IDLE Shell窗口输出测量值大于等于9的行数据。
code.python
>>> == RESTART: D:/Samples/1.py =
测量值
时间
2022-03-18 01:00:00 9
2022-03-18 03:00:00 9
2022-03-18 05:00:00 10
2022-03-18 17:00:00 10
2022-03-19 10:00:00 9
2022-03-19 17:00:00 9
2022-03-20 02:00:00 10
……
数据转换
【问题描述】
用匿名函数或自定义函数对已有列数据进行转换得到新列或修改原列数据。
【示例7-5】
本例使用示例7-2的数据,试用匿名函数给每个测量值加上一个0-1之间不同的随机数。
- 编写下面的代码:
code.python
import pandas as pd
import numpy as np
# 读取Excel文件
file_path = "D:/Samples/ch07/01 时间序列数据/时间序列.xlsx"
df = pd.read_excel(file_path, sheet_name=0, index_col=0, engine="openpyxl")
# 使用匿名函数给每个测量值加上一个0-1之间不同的随机数
df = df.applymap(lambda x: x + np.random.uniform(0, 1))
# 输出处理后的结果
print(df)
打开Python IDLE,新建一个脚本文件,将上面生成的代码复制进去,保存。运行脚本,在IDLE Shell窗口输出添加随机数后的测量值。
code.python
>>> == RESTART: D:/Samples/1.py =
测量值
时间
2022-03-18 00:00:00 5.668738
2022-03-18 01:00:00 9.132018
2022-03-18 02:00:00 6.967579
2022-03-18 03:00:00 9.543182
2022-03-18 04:00:00 8.467535
... ...
2022-03-21 23:00:00 1.449208
2022-03-22 00:00:00 5.640166
2022-03-22 01:00:00 10.106665
2022-03-22 02:00:00 6.671021
2022-03-22 03:00:00 9.527271
[100 rows x 1 columns]
数据汇总
【问题描述】
对指定时间段内的数据进行汇总。
【示例7-6】
本例使用示例7-2的数据,请汇总每一天的测量值。
- 编写下面的代码:
code.python
import pandas as pd
# 使用pandas读取Excel文件中第1个工作表中的数据
df = pd.read_excel('D:/Samples/ch07/01 时间序列数据/时间序列.xlsx', engine='openpyxl', sheet_name=0, index_col=0)
# 将索引列设为日期格式
df.index = pd.to_datetime(df.index)
# 按月份进行汇总
monthly_summary = df.resample('D').sum()
# 输出结果
print(monthly_summary)
打开Python IDLE,新建一个脚本文件,将上面生成的代码复制进去,保存。运行脚本,在IDLE Shell窗口输出每天的汇总数据。
code.python
>>> == RESTART: D:/Samples/1.py =
测量值
时间
2022-03-18 133
2022-03-19 106
2022-03-20 146
2022-03-21 119
2022-03-22 30